package com.lx.commonlib.utils;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import java.util.HashMap;
import java.util.Map;

/**
 * 类说明：工具类中持有一个UI线程的Handler,用来执行需要运行在UI线程的任务和 发送消息到UI线程
 * Created by liuxiong on 2019/3/22.
 */

public class UIHandlerUtil {
    private static final String TAG="xxx" +UIHandlerUtil.class.getSimpleName();

    private static UIHandlerUtil instance;

    private HashMap<String ,MessageListener> listeners;

    private Handler mHandler;

    private UIHandlerUtil(){
        listeners=new HashMap<>();

        mHandler=new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
//                            super.handleMessage(msg);
                for(Map.Entry<String, MessageListener> entry: listeners.entrySet())
                {
                    Log.d(TAG,"Key: "+ entry.getKey());
                    if(entry.getValue()!=null){
                        entry.getValue().handleMessage(msg);
                    }
                }
            }
        };
    }

    /**
    * 方法说明:  获取实例
    * @return 返回一个UIHandlerUtil的实例
    * created by liuxiong on 12:26
    */
    public static UIHandlerUtil getInstance(){
        if(instance==null){
            synchronized (UIHandlerUtil.class){
                if(instance==null){
                    instance=new UIHandlerUtil();
                }
            }
        }
        return instance;
    }

    /**
    * 方法说明:  获取UI线程的handler
    * @return
    * created by liuxiong on 13:18
    */
    public Handler getHandler(){
        return mHandler;
    }

    /** 以下方法 */
    public void post(Runnable runnable){
        mHandler.post(runnable);
    }

    public void postAtTime(Runnable runnable,long uptimeMillis){
        mHandler.postAtTime(runnable,uptimeMillis);
    }

    public void postDelayed(Runnable runnable,long delayMillis){
        mHandler.postDelayed(runnable,delayMillis);
    }

    public void sendMessage(Message message){
        mHandler.sendMessage(message);
    }

    public void sendMessageAtTime(Message message,long uptimeMillis){
        mHandler.sendMessageAtTime(message,uptimeMillis);
    }

    /**
    * 方法说明:  设置消息监听,
    * @param  tag 用来标记listener，以便在需要移除的时候移除监听,可以使用类名，只要唯一就行了
    * created by liuxiong on 2019/3/22 12:09
    */
    public void setMessageListener(String tag,MessageListener listener){
        listeners.put(tag,listener);
    }

    /**
    * 方法说明:
    * @param  tag 设置监听时添加的标记，用来移除对应的监听
    * created by liuxiong on 2019/3/22 12:15
    */
    public void removeMessageListener(String tag){
        listeners.remove(tag);
    }

    /**
    *  类说明：接收消息的监听
    *  created by liuxiong on 2019/3/22
    **/
    public interface MessageListener{

        void handleMessage(Message msg);
    }
}
